// var orderbill = require('../../js/shop/order.js').order
const chooseLocation = requirePlugin('chooseLocation');
var actmember = require('../../../xc/model/member');
var paytool = require('./js/paytool');

// var util = require('../../../utils/util.js');
var actcart = require('../../../xc/sys/cart')
var wsactcart = require('../../../xc/sys/purchaseorder')

var acttoolv2 = require('../../../xc/sys/toolv2')
var order_bill = require('../model/order_bill.js')
var actcouponbill = require('../../../xc/model/coupon_cont')
// var actpacklistbill = require('../../../model/pack_list')
var actpacklistbill = require('../model/pack_list')
var order_inquirybill = require('../model/order_inpuirybill')

import Notify from '../../../vant/weapp/notify/notify';
var app = getApp();
Page({
  mixins: [require('../../../xc/mixins/basicMixin')],
  /**
   * 页面的初始数据
   */
  data: {
    calcsamecityinfo: null,
    delivery_config: null,
    expressaddr: null,
    //订单默认参数
    paytype: -1, //支付类型1.微信支付
    // 导航
    nav: [],
    navCur: -1,
    deliverymode: 1, //navCur =0 的有效  1自提  2团长配送    
    activitymodel: {
      clienttimestampdeviation: 0, //服务器跟客户端 的时间误差
      haslimite: false,
      intervalid: -1 //自己执行判断   
    },
    priceinfo: {},
    freight: 0, //快递费   actcoupon  freight paytype expressaddr paytype deliverymode
    actcoupon: null,
    actclub: null,
    remark: "",
    iscart: "-1",
    memberinfo: null,
    paymentmethod: [],
    clubdelivery: 0, //1自提 2配送
    // balanceloadsuccess: false,
    pageshow: true,
    submitstatus: false, //提交按钮状态
    chosedtimeshow: false,
    delivertime: "",
    minDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    packinfo: null,
    iconmode: '1',
    unit: '￥',
    templists: null,
    deposit:30
  },
  //！！！加载完成加载
  xcloaddata: function (options, config) {


    var that = this;
    var app = getApp();

    // this.setconfig(config)

    var update = {}
    if(options.inquiryuid){
      update['inquiryuid']=options.inquiryuid
    }
    var deposit = 30;
    if (config.wholesale) {
      var wholesaleconfig = config.wholesale;
      if (wholesaleconfig && wholesaleconfig.warehouse && wholesaleconfig.warehouse.deposit) {
        deposit = wholesaleconfig.warehouse.deposit
      }
    }
    update['deposit']=deposit
    // if (config.wholesale) {

    //   update['wholesaleconfig'] = config.wholesale
    // }
    this.setData(update)



    var app = getApp()
    var cartdadta = app.globalData.depcart["data"]
    // console.log("oooooooooooooooooooooooooooooooooooooooo")
    // console.log(JSON.stringify(cartdadta) )
    // var cartdadta = '[{"guigetype":"1","about":"印计谷羽","id":"226","name":"(演示)渔夫帽女日系百搭防晒遮阳帽夏季做旧韩版原宿港风帽子","simg":"https://cx002exrds.7mx7.com/images/5/2021/03/GxlXqQi460lsKkUb1p60I1ZB1i16L1.jpg","skudata":{"grouplabel":[{"grouptitle":"颜色","attrs":[{"name":"卡其色","simg":"https://cx002exrds.7mx7.com/images/5/2021/10/vk3vzOeDUKb10g19edwsw913KB9R9r.png"},{"name":"茶色","simg":"https://cx002exrds.7mx7.com/images/5/2021/10/VisfzU8UMFNnMsOfG68QIKqIfI0OEk.png"},{"name":"黑色","simg":"https://cx002exrds.7mx7.com/images/5/2021/10/jKx5qX0q05qQpqf005XbkScXfYrfyc.png"}],"imgstatus":"1"},{"grouptitle":"大小","attrs":[{"name":"大","simg":""},{"name":"小","simg":""}],"imgstatus":"-1"},{"grouptitle":"年限","attrs":[{"name":"一年","simg":""},{"name":"两年","simg":""}],"imgstatus":"-1"}],"stockdata":[{"price":"10000","costprice":"5000","realprice":"8000","temno":"","stock":"100","weight":"0","fullsimg":"","simgname":"","simg":"","isshow":-1,"isdefault":"-1"},{"price":"10000","costprice":"5000","realprice":"8000","temno":"","stock":"0","weight":"0","fullsimg":"","simgname":"","simg":"","isshow":-1,"isdefault":"-1"},{"price":"10000","costprice":"5500","realprice":55,"temno":"","stock":"1","weight":"0","fullsimg":"","simgname":"","simg":"","isshow":1,"isdefault":"-1"},{"price":"10000","costprice":"5500","realprice":55,"temno":"","stock":"1","weight":"0","fullsimg":"","simgname":"","simg":"","isshow":1,"isdefault":"-1"},{"price":"10000","costprice":"5000","realprice":"8000","temno":"","stock":"100","weight":"0","fullsimg":"","simgname":"","simg":"","isshow":-1,"isdefault":"-1"},{"price":"10000","costprice":"5000","realprice":"8000","temno":"","stock":"100","weight":"0","fullsimg":"","simgname":"","simg":"","isshow":-1,"isdefault":"-1"},{"price":"10000","costprice":"5000","realprice":"8000","temno":"","stock":"100","weight":"0","fullsimg":"","simgname":"","simg":"","isshow":-1,"isdefault":"-1"},{"price":"10000","costprice":"7200","realprice":72,"temno":"","stock":"1","weight":"0","fullsimg":"","simgname":"","simg":"","isshow":1,"isdefault":"-1"},{"price":"10000","costprice":"5000","realprice":"8000","temno":"","stock":"100","weight":"0","fullsimg":"","simgname":"","simg":"","isshow":-1,"isdefault":"-1"},{"price":"10000","costprice":"6440","realprice":64.4,"temno":"","stock":"48","weight":"0","fullsimg":"","simgname":"","simg":"","isshow":1,"isdefault":"-1"},{"price":"10000","costprice":"5000","realprice":"8000","temno":"","stock":"100","weight":"0","fullsimg":"","simgname":"","simg":"","isshow":-1,"isdefault":"-1"},{"price":"10000","costprice":"5000","realprice":"8000","temno":"","stock":"100","weight":"0","fullsimg":"","simgname":"","simg":"","isshow":-1,"isdefault":"-1"}],"len":"3","cartesianproduct":[[{"name":"卡其色","simg":"https://cx002exrds.7mx7.com/images/5/2021/10/vk3vzOeDUKb10g19edwsw913KB9R9r.png"},{"name":"大","simg":""},{"name":"一年","simg":""}],[{"name":"卡其色","simg":"https://cx002exrds.7mx7.com/images/5/2021/10/vk3vzOeDUKb10g19edwsw913KB9R9r.png"},{"name":"大","simg":""},{"name":"两年","simg":""}],[{"name":"卡其色","simg":"https://cx002exrds.7mx7.com/images/5/2021/10/vk3vzOeDUKb10g19edwsw913KB9R9r.png"},{"name":"小","simg":""},{"name":"一年","simg":""}],[{"name":"卡其色","simg":"https://cx002exrds.7mx7.com/images/5/2021/10/vk3vzOeDUKb10g19edwsw913KB9R9r.png"},{"name":"小","simg":""},{"name":"两年","simg":""}],[{"name":"茶色","simg":"https://cx002exrds.7mx7.com/images/5/2021/10/VisfzU8UMFNnMsOfG68QIKqIfI0OEk.png"},{"name":"大","simg":""},{"name":"一年","simg":""}],[{"name":"茶色","simg":"https://cx002exrds.7mx7.com/images/5/2021/10/VisfzU8UMFNnMsOfG68QIKqIfI0OEk.png"},{"name":"大","simg":""},{"name":"两年","simg":""}],[{"name":"茶色","simg":"https://cx002exrds.7mx7.com/images/5/2021/10/VisfzU8UMFNnMsOfG68QIKqIfI0OEk.png"},{"name":"小","simg":""},{"name":"一年","simg":""}],[{"name":"茶色","simg":"https://cx002exrds.7mx7.com/images/5/2021/10/VisfzU8UMFNnMsOfG68QIKqIfI0OEk.png"},{"name":"小","simg":""},{"name":"两年","simg":""}],[{"name":"黑色","simg":"https://cx002exrds.7mx7.com/images/5/2021/10/jKx5qX0q05qQpqf005XbkScXfYrfyc.png"},{"name":"大","simg":""},{"name":"一年","simg":""}],[{"name":"黑色","simg":"https://cx002exrds.7mx7.com/images/5/2021/10/jKx5qX0q05qQpqf005XbkScXfYrfyc.png"},{"name":"大","simg":""},{"name":"两年","simg":""}],[{"name":"黑色","simg":"https://cx002exrds.7mx7.com/images/5/2021/10/jKx5qX0q05qQpqf005XbkScXfYrfyc.png"},{"name":"小","simg":""},{"name":"一年","simg":""}],[{"name":"黑色","simg":"https://cx002exrds.7mx7.com/images/5/2021/10/jKx5qX0q05qQpqf005XbkScXfYrfyc.png"},{"name":"小","simg":""},{"name":"两年","simg":""}]]},"skuht":{"0_0_0":{"index":0,"stock":100,"isshow":-1,"weight":"0","isdefault":"-1","simg":"","fullsimg":"","price":"10000","realprice":"8000","num":0,"key":["0","0","0"]},"0_0_1":{"index":1,"stock":0,"isshow":-1,"weight":"0","isdefault":"-1","simg":"","fullsimg":"","price":"10000","realprice":"8000","num":0,"key":["0","0","1"]},"0_1_0":{"index":2,"stock":1,"isshow":1,"weight":"0","isdefault":"-1","simg":"","fullsimg":"","price":"10000","realprice":55,"num":1,"key":["0","1","0"],"uid":"84"},"0_1_1":{"index":3,"stock":1,"isshow":1,"weight":"0","isdefault":"-1","simg":"","fullsimg":"","price":"10000","realprice":55,"num":1,"key":["0","1","1"],"uid":"84"},"1_0_0":{"index":4,"stock":100,"isshow":-1,"weight":"0","isdefault":"-1","simg":"","fullsimg":"","price":"10000","realprice":"8000","num":0,"key":["1","0","0"]},"1_0_1":{"index":5,"stock":100,"isshow":-1,"weight":"0","isdefault":"-1","simg":"","fullsimg":"","price":"10000","realprice":"8000","num":0,"key":["1","0","1"]},"1_1_0":{"index":6,"stock":100,"isshow":-1,"weight":"0","isdefault":"-1","simg":"","fullsimg":"","price":"10000","realprice":"8000","num":0,"key":["1","1","0"]},"1_1_1":{"index":7,"stock":1,"isshow":1,"weight":"0","isdefault":"-1","simg":"","fullsimg":"","price":"10000","realprice":72,"num":0,"key":["1","1","1"]},"2_0_0":{"index":8,"stock":100,"isshow":-1,"weight":"0","isdefault":"-1","simg":"","fullsimg":"","price":"10000","realprice":"8000","num":0,"key":["2","0","0"]},"2_0_1":{"index":9,"stock":48,"isshow":1,"weight":"0","isdefault":"-1","simg":"","fullsimg":"","price":"10000","realprice":64.4,"num":0,"key":["2","0","1"]},"2_1_0":{"index":10,"stock":100,"isshow":-1,"weight":"0","isdefault":"-1","simg":"","fullsimg":"","price":"10000","realprice":"8000","num":0,"key":["2","1","0"]},"2_1_1":{"index":11,"stock":100,"isshow":-1,"weight":"0","isdefault":"-1","simg":"","fullsimg":"","price":"10000","realprice":"8000","num":0,"key":["2","1","1"]}},"unit":"顶","attrs":{"0_1_0":{"index":2,"stock":1,"isshow":1,"weight":"0","isdefault":"-1","simg":"","fullsimg":"","price":"10000","realprice":55,"num":1,"key":["0","1","0"],"uid":"84"},"0_1_1":{"index":3,"stock":1,"isshow":1,"weight":"0","isdefault":"-1","simg":"","fullsimg":"","price":"10000","realprice":55,"num":1,"key":["0","1","1"],"uid":"84"}}}]'

    // cartdadta = JSON.parse(cartdadta)
    this.setData({
      cartdadta: cartdadta
    })
    this.billpriceinfo()

    this.getPaymethod(config)

  },
  //！！！获取支付方式
  getPaymethod(config) {
    var paytype = -1
    var allpaymentmethod = [{
        val: 1,
        name: "微信支付"
      }, {
        val: 2,
        name: "余额支付"
      },
      // {
      //   val: 4,
      //   name: "货到付款"
      // }, {
      //   val: 8,
      //   name: "好友代付"
      // }
    ]
    var paymentmethod = []
    allpaymentmethod.forEach(item => {
      if ((item.val & config["payment"].mode) == item.val) {
        if (paytype == -1) {
          paytype = item.val
        }
        if (item.val == 2 && config["payment"]['balancepayname']) {
          item['name'] = config["payment"]['balancepayname'] + '支付'
        }
        paymentmethod.push(item)
      }
    })

    this.setData({
      paytype:paytype,
      paymentmethod: paymentmethod
    })
  },
  //！！！登录
  afterlogin(options, configdata, userinfo) {
    this.setData({
      memberinfo: userinfo.memberinfo
    })
    //最新vip会员最新余额
    this.updatesimplevipinfo();
  },
  //计算价格
  billpriceinfo: function () {
    // 获取几折定金价格
    var deposit=this.data.deposit
    var pronums = 0; //总数量
    var prototalprice = 0; //商品总金额

    var cartdadta = this.data.cartdadta
    for (var a in cartdadta) {
      var item = cartdadta[a];
      for (var s in item['attrs']) {
        prototalprice += (item['attrs'][s]["realprice"] * 100) * item['attrs'][s]["num"];
        pronums += item['attrs'][s]["num"]
      }

    }

    var totalprice = prototalprice; //订单总价

    //  totalprice = prototalprice 
    var paymoney = totalprice * deposit * 0.01
    paymoney = Math.round(paymoney)


    var total = {};
    total['pronums'] = pronums;
    total['totalprice'] = totalprice;
    total['paymoney'] = paymoney;



    console.log("total")

    console.log(total)
    this.setData({
      priceinfo: total
    })

    // this.selectComponent('#van-submit-bar').updatePrice()
    // if (this.data.activitymodel.haslimite) {
    //   this.autoexcel();
    // }

  },
  //获取模板消息弹框---暂时不用
  getTemplists() {
    var that = this;
    order_bill.gettemplist().then(function (res) {
      if (res['status'] == 1) {
        that.setData({
          templists: res['obj']
        })
      }
    })
  },
  //1.创建订单  
  createbill: function (e) {
    // this.queryOrder(6)
    // return;
    // ordermodel
    var app = getApp()
    var that = this;
    var ordermodel = {};
    //订单内容
    
   
    var htpro = {};

      if (this.data.inquiryuid) {
        ordermodel["inquiryuid"] = this.data.inquiryuid;
      }
      that.data.cartdadta.forEach(function (item) {
      

        var attrs = {}
        if (item['guigetype'] == 1) {
          for (var i in item['attrs']) {
            var items = {
              key: i,
              num: item['attrs'][i]['num']
            }
            if (item['attrs'][i]['realprice']) {
              items['realprice'] = item['attrs'][i]['realprice'] * 100
            }
            attrs[item['attrs'][i]["index"]] = items
          }
        } else {
          attrs["-1"] = {
            key: -1,
            num: item['attrs'][-1]['num']
          }
        }
        htpro[item["id"]] = attrs
      })


    ordermodel["htpro"] = htpro;

  
 
   
    var publicdata = ['paytype'];
    for (var i in publicdata) {
      ordermodel[publicdata[i]] = this.data[publicdata[i]]
    }

    this.postorder(ordermodel)

  },
  //2.提交订单
  postorder(ordermodel) {
    var that = this;
  
  
    that.showTemplists(ordermodel)
   


  },
  //3.弹出订阅消息框
  showTemplists(ordermodel) {
    var that = this
    var templists = this.data.templists;
    if (templists) {
      var distributionmode = ordermodel['distributionmode'];
      var key = "";
      if (distributionmode == 1) {
        key = "notice_order";
      } else if ((distributionmode & 16) == 16) {
        key = "notice_cluborder_deliver";
      } else {
        key = "notice_cluborder_self";
      }
      var template_ids = []
      if (key && templists[key]) {
        template_ids = templists[key]
      }

      if (template_ids && template_ids.length > 0) {
        if (template_ids.length > 3) {
          template_ids = template_ids.slice(0, 3)
        }

        wx.requestSubscribeMessage({
          tmplIds: template_ids,
          success(res) {},
          fail(res) {},
          complete(res) {
            that.thenpostorder(ordermodel)
          }
        })
      } else {
        that.thenpostorder(ordermodel)

      }


    } else {
      this.thenpostorder(ordermodel)
    }
  },
  //4.传送订单
  thenpostorder(ordermodel) {
    var that = this;
    that.setData({
      submitstatus: true
    })

    order_inquirybill.createdepositorder(ordermodel).then(function (restmodel) {
      console.log("restmodel")
      console.log(restmodel)

      if (restmodel["status"] == 1) {
         if (restmodel["paytype"] == 1 || restmodel["paytype"] == 3) {
          var pay_params = restmodel["pay_params"];

            wx.requestPayment({
              timeStamp: pay_params["timeStamp"],
              nonceStr: pay_params["nonceStr"],
              package: pay_params["package"],
              signType: pay_params['signType'],
              paySign: pay_params["paySign"],
              success(res) {
                // that.showtemplate(template_ids, restmodel['ordernum'], restmodel["id"])

               
                that.setData({
                  submitstatus: false
                })
              },
              fail(res) {
                if (res["errMsg"] == "requestPayment:fail cancel") {
                  wx.showModal({
                    title: '订单未支付',
                    content: '订单未支付',
                    showCancel: false,
                    success(res) {


                      wx.redirectTo({
                        url: "/xc_lshop/shop/order/inquiry",
                      })
                    }
                  })
                }
                that.setData({
                  submitstatus: false
                })
              }
            })
        

        } else if (restmodel["paytype"] == 2 || restmodel["paytype"] == 0) {
          //余额支付
          wx.redirectTo({
            url: '/xc_lshop/shop/order/inquiry',
          })
          // that.showtemplate(template_ids, restmodel['ordernum'], restmodel["id"])
          that.setData({
            submitstatus: false
          })
        }
      } else {
        wx.showModal({
          title: '错误',
          content: restmodel["message"],
        })
        that.setData({
          submitstatus: false
        })
      }
    })
  },
  queryOrder(id){
    var that=this;
    order_inquirybill.queryorder(id,1).then(function (queryreslut) {
      if (queryreslut["status"] == 1) {
        wx.redirectTo({
          url: '/xc_lshop/shop/order/inquiry',
        })
        // that.showtemplate(template_ids, restmodel['ordernum'], restmodel["id"])

      }
    })
  },
  updatesimplevipinfo() {
    var that = this;
    actmember.simplevipinfo().then(function (res) {
      if (res["status"] == 1 && res["obj"]) {
        var updatemodel = {}
        updatemodel["memberinfo.goldcoin"] = res["obj"]["goldcoin"]
        updatemodel["memberinfo.amount"] = res["obj"]["amount"]
        updatemodel["memberinfo.vips"] = res["obj"]["vips"]
      }
      that.setData(updatemodel)
    })
  },
  //获取仓库商品信息
  getwhproinfo(proid) {
    var that = this;
    order_bill.getwhproinfo(proid).then(function (res) {
      if (res['status'] == 1) {
        var cartdadta = [];
        cartdadta.push(res['obj'])
        that.setData({
          cartdadta: cartdadta
        })
        that.changnav(that.data.clubdelivery, that.data.expressaddr)
      } else {
        that.error(res['message'], true)
      }
    })
  },
  onChangeNum(e) {
    var index = e.currentTarget.dataset.index
    var idx = e.currentTarget.dataset.idx;
    var name = "cartdadta[" + index + "].attrs[" + idx + "].num";
    this.setData({
      [name]: e.detail
    })

  },
  onmodeChange(e) {
    console.log(e)
    this.setData({
      iconmode: e.detail
    })
    this.billpriceinfo()
  },
  selectchange(e) {
    var status = e.detail;
    this.setData({
      pageshow: status
    })
  },
  /**
   * 选择优惠券
   */
  paytypeChange(e) {

    this.setData({
      paytype: e.detail
    })
  },

  //弹出配送时间选择
  showdelivertime() {
    var startDate = Date.parse(new Date());
    var orderconfig = this.data.orderconfig;
    var addtype = orderconfig.deliveryaftertype
    var addtime = orderconfig.deliveryaftertime
    if (addtype == 1) {
      addtime = addtime * 60 * 1000;
    } else if (addtype == 2) {
      addtime = addtime * 60 * 60 * 1000;
    } else if (addtype == 3) {
      addtime = addtime * 60 * 60 * 24 * 1000;
    }
    startDate = startDate + addtime;

    this.setData({
      minDate: startDate,
      chosedtimeshow: true
    })
  },
  ontimeConfirm(event) {


    var date = new Date(event.detail);

    var timedate = this.formatter(date)
    this.setData({
      chosedtimeshow: false,
      delivertime: timedate,
    });
  },
  formatter(date) {
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
  },
  deletetime() {
    if (this.data.delivertime) {
      this.setData({
        delivertime: ""
      })
    }
  },



  usecoupon() {
    var that = this;
    this.authop("coupon").then(rest => {
      if (rest["status"] != 1) {
        wx.showToast({
          title: rest["message"] ? rest["message"] : "获取信息失败",
        })
      } else {
        var userinfo = rest["userinfo"]
        var Comcouponpro = that.selectComponent("#couponpro")
        Comcouponpro.showinfo()
      }
    })
  },

  click_nav(e) {
    var that = this;
    this.setData({
      navCur: e.currentTarget.dataset.id,
      freight: 0
    })
    this.changnav()
  },
  changnav(clubdelivery, expressaddr) {

    var navCur = this.data.navCur


    if (navCur == 0 || navCur == 3) {

      var address = this.selectComponent("#address");
      address.set_init(navCur);
    } else if (navCur == 1 || navCur == 2) {
      this.setData({
        clubdelivery: 0
      })
      var address = this.selectComponent("#clubaddress");
      address.set_init(navCur, clubdelivery, expressaddr);
    }
    this.billpriceinfo();
  },

  //选择优惠券回调
  couponblack(e) {
    var coupon = e.detail
    if (coupon) {
      var discountmoney = actcouponbill.discountmoney(coupon, this.data.cartdadta)
      coupon["discountmoney"] = discountmoney
    }
    this.setData({
      actcoupon: coupon
    })
    this.billpriceinfo()
  },
  setconfig(config) {

    var update = {};
    if (config.yihuo) {
      update['yihuoconfig'] = config.yihuo
    }
    if (config.payment) {
      update['paymentconfig'] = config.payment
      update['unit'] = config.payment.balancepayunit

    }

    if (config.sys_business_config) {
      update['businessconfig'] = config.sys_business_config
    }

    if (config.task) {
      update['taskconfig'] = config.task
      update['taskname'] = config.task.taskname
    }

    var orderconfig = config['order'];
    if (!orderconfig['deliverytimestatus']) {
      orderconfig['deliverytimestatus'] = -1;
    }
    update['orderconfig'] = orderconfig



    if (config.vip) {
      if (config.vip.status == 1) {
        var rank = config.vip.rank;
        update['viprank'] = rank
      }
    }
    if (config.wholesale) {
      update['wholesaleconfig'] = config.wholesale
    }
    this.setData(update)

  },
  judgeorder() {
    var that = this;
    var businessconfig = this.data.businessconfig
    var scenedata = wx.getLaunchOptionsSync()
    this.setData({
      scene: scenedata['scene']
    })

    wx.getSystemInfo({
      success(res) {
        var version = res.SDKVersion;
        version = version.replace(/\./g, "")

        if (version >= 2230) {
          wx.checkBeforeAddOrder({
            success(res) {

              // if (res && res['data'] && ((res['data']['requiredFundType'] != 0) || (businessconfig && businessconfig.wxtransation && businessconfig.wxtransation.teststatus == 1))) {

              //   that.setData({
              //     traceId: res['data']['traceId']
              //   })

              // }
            },
            fail(res) {


            }
          })
        }

      }
    })
  },

  getcardmodel(id) {
    var that = this;
    var cartdadta = this.data.cartdadta
    actpacklistbill.getmodel(id).then(res => {
      if (res['status'] == 1) {
        // html2wxml.html2wxml('article', res.obj.htmlcont, that, 5);



        if (res['obj']['proinfo']) {
          var proinfo = res['obj']['proinfo'];

          var prokeyinfo = {};
          for (var i in proinfo) {

            prokeyinfo[proinfo[i]['id']] = {
              restnum: proinfo[i]['allnum'] - proinfo[i]['usednum'],
              activityprice: proinfo[i]['proinfo']['activityprice']
            }
          }

          res['obj']['prokeyinfo'] = prokeyinfo
        }


        that.setData({
          packinfo: res['obj']
        })
      } else {
        that.error(res['message'], true)
      }

    })
  },
  getclubinfo(id) {


    var that = this
    actmember.getmycloubinfo(id).then(res => {


      if (res["status"] == 1) {
        var clubinfo = res["obj"]
        if (app.globalData.lng) {
          var preslut = acttoolv2.distanceByLnglat(app.globalData.lng, app.globalData.lat, clubinfo.lng, clubinfo.lat)
          clubinfo["juli"] = preslut["formatval"] + preslut["unit"];
        }
        app.globalData.clubinfo = clubinfo;
        that.changnav()
      }
    })


  },
  getmycloubinfo() {
    var app = getApp()
    if (!app.globalData.clubinfo) {
      actmember.getmycloubinfo().then(res => {
        if (res["status"] == 1) {
          var clubinfo = res["obj"]
          if (app.globalData.lng) {
            var preslut = acttoolv2.distanceByLnglat(app.globalData.lng, app.globalData.lat, clubinfo.lng, clubinfo.lat)
            clubinfo["juli"] = preslut["formatval"] + preslut["unit"];
          }
          app.globalData.clubinfo = clubinfo;
        }
      })
    }
    // app.globalData.clubinfo 

  },

  //针对门店配送计算
  shopdeliverychage(ev) {
    var detail = ev.detail
    if (detail.clubdelivery == 1) {
      this.setData({
        clubdelivery: 1,
        freight: 0
      })
      this.data.expressaddr = null
      this.billpriceinfo();
    } else if (detail.clubdelivery == 2) {
      this.setData({
        clubdelivery: 2,
      })
      if (detail.obj) {
        this.calcsamecity(null, detail.obj["distance"])
        this.data.expressaddr = detail.obj
      }
    }
  },
  //同城快递计算
  calcsamecity(intracity, distance) {
    if (!intracity) {
      intracity = this.data.delivery_config.intracity;
    }
    if (!intracity) {
      return;
    }
    if (!distance) {
      var expressaddr = this.data.expressaddr
      distance = expressaddr.distance;
    }
    var {
      calcsamecityinfo,
      freight
    } = paytool.calcsamecity(intracity, distance)
    if (calcsamecityinfo["status"] == 1) {
      this.setData({
        calcsamecityinfo,
        freight
      })
      this.billpriceinfo();
    } else {
      this.data.calcsamecityinfo = calcsamecityinfo;
    }


  },
  //获取运费
  getexpress: function (pro, addr) {

    var that = this;
    if (!pro) {
      pro = this.data.cartdadta
    }
    if (!addr) {
      addr = this.data.expressaddr
    }
    if (pro && addr) {
      if (that.data.navCur == 3) {
        this.calcsamecity();
        return;
      }
      order_bill.getexpress(pro, addr).then(function (paradata) {
        if (paradata.failnum > 0) {} else {
          that.setData({
            freight: paradata.totalmoney
          })
        }
        that.billpriceinfo();
      })
    }
  },
  //改地址切换运费
  selectaddrfunc: function (e) {
    this.data.expressaddr = e.detail;
    if (e.detail != null) {
      this.getexpress(this.data.cartdadta, e.detail)
    }

  },
  //改团点地址切换运费 
  selectgroupaddr: function (e) {
    this.data.actclub = e.detail
    var that = this;

    this.setData({
      freight: 0
    })
    that.billpriceinfo();
  },

  autoexcel: function () {
    var that = this;
    if (that.data.activitymodel.intervalid != -1) {
      clearInterval(that.data.activitymodel.intervalid)
    }
    that.data.activitymodel.intervalid = setInterval(function () {
      that.setData({
        "list": that.data.list
      });
    }, 1000)
  },
  onchosedtimeClose() {
    this.setData({
      chosedtimeshow: false
    })
  },

  showtemplate(template_ids, ordernum, id) {
    var that = this;
    console.log("ddddddddddddddddddddddddddddddddddddddddddddddd")
    console.log(template_ids)

    if (template_ids && template_ids.length > 0) {
      if (template_ids.length > 3) {
        template_ids = template_ids.slice(0, 3)
      }

      wx.requestSubscribeMessage({
        tmplIds: template_ids,
        success(res) {
          console.log("success9999999999999999999")
          console.log(res)
          that.sendnotice_buy(ordernum)
        },
        fail(res) {
          console.log("fail8888888888888888888888")
          console.log(res)

        },
        complete(res) {

          wx.redirectTo({
            url: '/xc_lshop/shop/paycore/paysuccess?id=' + id,
          })
        }
      })
    } else {

      wx.redirectTo({
        url: '/xc_lshop/shop/paycore/paysuccess?id=' + id,
      })
    }
  },
  sendnotice_buy(ordernum) {
    order_bill.sendnotice_buy(ordernum).then(function (restmodel) {
      console.log(restmodel)
    })
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //系统组件选择地址回调
    // const location = chooseLocation.getLocation();
    // if (location) {
    //   var address = null
    //   if (this.data.navCur == 0 || this.data.navCur == 3) {

    //     address = this.selectComponent("#address");
    //   } else if (this.data.navCur == 1 || this.data.navCur == 2) {


    //     address = this.selectComponent("#clubaddress");
    //   }


    //   address.chooseLocation(location)

    // }
  },



})